<template>
  <div class="rank-con" ref="rankBox"></div>
</template>

<script lang="ts">
import { defineComponent, onMounted, onUnmounted, reactive, toRefs, ref, useContext, watch } from 'vue'
import axios from '../api'
import { useStore } from 'vuex'
import { rankColorArr } from '../config'
import WebSocketSerivce from '../utils/socket_service'
declare const echarts
export default defineComponent({
  name: 'rank',
  setup() {
    const store = useStore()
    let rankChart
    let data
    let timeId
    let startValue = 0
    let endValue = 9
    const rankBox = ref<HTMLElement>(null)

    watch(() => store.state.theme, theme => {
        rankChart.dispose()  // 销毁原来的图表
        initChart()
        screenAdapter()
        updateChart()
      })
    // 初始化图表
    const initChart = async () => {
      rankChart = echarts.init(rankBox.value,store.state.theme)
     
      const initOption = {
        title: {
          text: '▎地区销售排行',
          left: 20,
          top: 20
        },
        // 控制坐标轴大小
        grid: {
          top: '40%',
          left: '5%',
          right: '5%',
          bottom: '5%',
          containLabel: true
        },
        // 工具提示
        tooltip: {
          show: true
        },
        xAxis: {
          type: 'category',
        },
        yAxis: {
          type: 'value',
        },
        series: {
          type: 'bar'
        }  
      }
      rankChart.setOption(initOption)

      rankChart.on('mousemove', () => {
        clearInterval(timeId)
      })
      rankChart.on('mouseout', setIntervalFn)
    
    }
    // 获取数据渲染图表
    const getData = res => {
      // const { data : res } = await axios.get('rank')
      data = res.sort((a, b) => {
        return b.value - a.value
      })
      updateChart()
      
    }
    // 更新图表
    const updateChart = () => { 
      const provinceArr =  data.map(item => item.name)
      const dataArr =  data.map(item => item.value)
      const updateOption = {
        xAxis: {
          data: provinceArr
        },
        series: {
          data: dataArr,
          itemStyle: {
            color: item => {
              let targetArr = []
              if(item.value > 300) {
                targetArr = rankColorArr[0]
              }else if(item.value > 200) {
                targetArr = rankColorArr[1]
              }else {
                targetArr = rankColorArr[2]
              }
              return new echarts.graphic.LinearGradient(
                  0,0,0,1,
                  [
                    {offset: 0, color: targetArr[0]},
                    {offset: 1, color: targetArr[1]}
                  ]
                )
            }
          }
        },
        // 区域缩放
        dataZoom: {
          show: false,
          startValue,
          endValue
        }
      }
      rankChart.setOption(updateOption)    
    }
    // 屏幕自适应
    const screenAdapter = () => {
      const titleFontSize = rankBox.value.offsetWidth / 100 * 3.6
      const adapterOption = { 
        title: {
          textStyle: {
            fontSize: titleFontSize
          }
        },
        series: [
          {
            barWidth: titleFontSize,
            itemStyle: {
              barBorderRadius: [titleFontSize / 2 , titleFontSize / 2, 0, 0]
            }
          }
        ]    
      }
      rankChart.setOption(adapterOption)
      rankChart.resize()
    }

    // 启动定时
    const setIntervalFn = () => {
      timeId = setInterval(() => {
        startValue += 1
        endValue += 1
        if(endValue > data.length - 1) {
          startValue = 0
          endValue = 9
        }
        updateChart()
      }, 2000);
    }

    const { expose } = useContext()
    expose({
      screenAdapter
    })

    onMounted(async () => {
      WebSocketSerivce.instance.registerCallBack('rankData', getData)
      initChart()
      // await getData()
      WebSocketSerivce.instance.send({
        action: 'getData',
        socketType: 'rankData',
        chartName: 'rank',
        value: false
      })
      window.addEventListener('resize', screenAdapter)
      screenAdapter()
      setIntervalFn()
    })

    onUnmounted(() => {
      WebSocketSerivce.instance.unRegisterCallBack('rankData')
      clearInterval(timeId)
      window.removeEventListener('resize', screenAdapter)
    })

    return {
      rankBox
    }
  }

})
</script>
<style lang="less" scoped>
.rank-con{
  width: 100%;
  height: 100%;
  overflow: hidden;
}
</style>
